<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nginx流式输出测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            margin-bottom: 20px;
        }
        input, select, button {
            padding: 10px;
            font-size: 16px;
            margin: 5px;
        }
        #output {
            border: 1px solid #ccc;
            padding: 10px;
            min-height: 300px;
            background-color: #f9f9f9;
            white-space: pre-wrap;
            font-family: monospace;
        }
        .error {
            color: red;
        }
        .info {
            color: blue;
        }
        .success {
            color: green;
        }
    </style>
</head>
<body>
    <h1>Nginx流式输出测试</h1>
    
    <div class="container">
        <label for="question">问题：</label>
        <input type="text" id="question" value="你好世界" size="30">
    </div>
    
    <div class="container">
        <label for="streamMode">流式模式：</label>
        <select id="streamMode">
            <option value="char">逐字符</option>
            <option value="word">逐词</option>
            <option value="chunk">分块</option>
            <option value="complete">完整</option>
        </select>
        <button onclick="startTest()">开始测试</button>
        <button onclick="clearOutput()">清空输出</button>
    </div>
    
    <div id="output"></div>

    <script>
        let eventSource = null;
        
        function startTest() {
            // 关闭之前的连接
            if (eventSource) {
                eventSource.close();
            }
            
            const question = document.getElementById('question').value;
            const streamMode = document.getElementById('streamMode').value;
            
            if (!question.trim()) {
                alert('请输入问题');
                return;
            }
            
            clearOutput();
            appendOutput('正在连接...', 'info');
            
            // 构建请求URL
            const url = `/api/nginx_stream/chat?question=${encodeURIComponent(question)}&stream_mode=${streamMode}`;
            
            try {
                eventSource = new EventSource(url);
                
                eventSource.onopen = function(event) {
                    appendOutput('连接已建立', 'success');
                };
                
                eventSource.onmessage = function(event) {
                    appendOutput('收到消息: ' + event.data);
                };
                
                eventSource.addEventListener('start', function(event) {
                    const data = JSON.parse(event.data);
                    appendOutput('[开始] ' + data.content, 'info');
                });
                
                eventSource.addEventListener('content', function(event) {
                    const data = JSON.parse(event.data);
                    appendOutput('[内容] ' + data.content, '', false);
                });
                
                eventSource.addEventListener('processed', function(event) {
                    const data = JSON.parse(event.data);
                    appendOutput('\n[处理完成] ' + data.content, 'success');
                });
                
                eventSource.addEventListener('stats', function(event) {
                    const data = JSON.parse(event.data);
                    appendOutput('[统计] ' + JSON.stringify(data, null, 2), 'info');
                });
                
                eventSource.addEventListener('error', function(event) {
                    const data = JSON.parse(event.data);
                    appendOutput('[错误] ' + data.content, 'error');
                });
                
                eventSource.addEventListener('end', function(event) {
                    const data = JSON.parse(event.data);
                    appendOutput('[结束] ' + data.content, 'info');
                    eventSource.close();
                });
                
                eventSource.onerror = function(event) {
                    appendOutput('连接错误: ' + JSON.stringify(event), 'error');
                    eventSource.close();
                };
            } catch (e) {
                appendOutput('创建连接时出错: ' + e.message, 'error');
            }
        }
        
        function appendOutput(text, className = '', append = true) {
            const output = document.getElementById('output');
            if (!append) {
                // 替换最后一行内容（用于流式字符显示）
                const lines = output.innerText.split('\n');
                if (lines.length > 0) {
                    lines[lines.length - 1] = text;
                    output.innerText = lines.join('\n');
                } else {
                    output.innerText = text;
                }
            } else {
                if (output.innerHTML !== '') {
                    output.innerHTML += '\n';
                }
                const div = document.createElement('div');
                div.className = className;
                div.textContent = getTextTime() + ' ' + text;
                output.appendChild(div);
            }
            // 滚动到底部
            output.scrollTop = output.scrollHeight;
        }
        
        function clearOutput() {
            document.getElementById('output').innerHTML = '';
        }
        
        function getTextTime() {
            const now = new Date();
            return '[' + now.getHours().toString().padStart(2, '0') + ':' + 
                   now.getMinutes().toString().padStart(2, '0') + ':' + 
                   now.getSeconds().toString().padStart(2, '0') + ']';
        }
    </script>
</body>
</html>